package logic

import (
	"context"
	"fmt"
	"month/model/mysql"
	"month/model/redis"
	"month/pkg"

	"month/userrpc/internal/svc"
	"month/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Rdb.Get("sendSmslogin" + in.Tel)
	if get.Val() == "" {
		return nil, fmt.Errorf("暂未获取短信验证码")
	}
	if get.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("短信验证码输入错误")
	}
	var user mysql.Users
	mysql.DB.Debug().Model(&mysql.Users{}).Where("tel=?", in.Tel).First(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该用户不存在")
	}
	if pkg.Md5(in.Password) != user.Password {
		return nil, fmt.Errorf("登录失败，密码错误")
	}
	redis.Rdb.Del("sendSmslogin" + in.Tel)
	return &userrpc.UserLoginResponse{Id: int64(user.ID)}, nil
}
